<template>
    <div>
        <n-grid :x-gap="24">
            <n-grid-item span="10">
              <n-form :label-width="100" label-placement="left" :model="sdTxt2ImgPrompt" :rules="rules" ref="formRef">
                <n-form-item label="提示词" path="prompt">
                  <n-input v-model:value="sdTxt2ImgPrompt.prompt" style="height: 100px" type="textarea" placeholder="请输出提示词" />
                    <n-button type="primary" style="margin-left: 6px;height: 100px;width: 80px" @click="show = !show" >
                        提示词库
                    </n-button>
                </n-form-item>
                <n-form-item label="反向提示词" path="negativePrompt">
                  <n-input placeholder="请输入反向提示词"  type="textarea" v-model:value="sdTxt2ImgPrompt.negativePrompt" />
                </n-form-item>
                <n-form-item label="seed" path="seed">
                  <n-input-number v-model:value="sdTxt2ImgPrompt.seed" />
                </n-form-item>
                <n-form-item label="sampler" path="sampler">
                    <n-select
                    :options="samplerOptions" v-model:value="sdTxt2ImgPrompt.samplerName" placeholder="请选择"
                    />
                 </n-form-item>
                  <n-form-item label="CfgScale" path="CfgScale">
                      <n-input-number v-model:value="sdTxt2ImgPrompt.cfgScale" />
                  </n-form-item>
                 <n-form-item label="Batch Size" path="Batch Size">
                    <n-input-number v-model:value="sdTxt2ImgPrompt.batchSize" />
                 </n-form-item>

                  <n-form-item label="Steps" path="Steps">
                      <n-input-number v-model:value="sdTxt2ImgPrompt.steps"/>
                  </n-form-item>
                  <n-form-item label="height" path="height">
                      <n-input-number v-model:value="sdTxt2ImgPrompt.height"/>
                  </n-form-item>
                  <n-form-item label="width" path="width">
                      <n-input-number v-model:value="sdTxt2ImgPrompt.width"/>
                  </n-form-item>
                <div>
                    <n-space aria-placeholder="left">
                        <n-button ghost>
                            重置
                        </n-button>
                        <n-button type="primary" @click="formSubmit" ghost>
                            生成
                        </n-button>
                    </n-space>
                </div>
              </n-form>
            </n-grid-item>
            <n-grid-item span="10">
                <n-card :segmented="{ content: false }"  >
                    <n-empty description="等待生成" v-if="taskStatus === 'waiting'">
                        <template #icon>
                            <n-icon>
                                <ios-airplane />
                            </n-icon>
                        </template>
                    </n-empty>
                    <n-space vertical v-if="taskStatus === 'SUBMITTED'">
                        <n-skeleton height="40px" width="33%" />
                        <n-skeleton height="40px" width="66%" :sharp="false" />
                        <n-skeleton height="40px" round />
                        <n-skeleton height="40px" circle />
                    </n-space>


                    <img v-if="taskStatus === 'SUCCESS'" :src="imageSrc" class="w-full" />

                </n-card>
            </n-grid-item>
      </n-grid>

        <n-drawer v-model:show="show" :width="drawerWidth">
            <n-drawer-content title="提示词选择器" closable>
                <promptTemplate prompt="8k" negative-prompt="low quality" @loadPrompt-event="loadPromptEvent"></promptTemplate>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script setup lang="ts">
  import {reactive, ref ,onMounted} from 'vue';
  import { useMessage } from 'naive-ui';
  import {sdControllerApi} from '@/api/sd/sdController.api'
  import promptTemplate from "@/components/prompt/promptTemplate.vue"

  const show = ref(false)
  const rules = {
    prompt: {
      required: true,
      message: '请输入提示词',
      trigger: 'blur',
    },
    mobile: {
      required: true,
      message: '请输入联系电话',
      trigger: 'input',
    },
  };

  const formRef: any = ref(null);
  const message = useMessage();
  const imageSrc = ref(); // 默认图片的URL
  const taskStatus = ref("waiting");
  const drawerWidth = ref(0)


  const sdTxt2ImgPrompt :SD.Txt2ImgInput =  reactive({
      prompt: '',
      negativePrompt: '',
      seed: -1,
      samplerName: 'DPM++ 2M Karras',
      batchSize: 1,
      steps: 20,
      width: 512,
      height: 512,
      promptEn: '',
      cfgScale: 7,
      savePath: ''
  });
  const samplerOptions =[
    {
        label: 'DPM++ 2M Karras',
        value: 'DPM++ 2M Karras'
    },
    {
        label: 'k_heun',
        value: 'k_heun'
    },
    {
        label: "k_euler",
        value: 'k_euler'
    },
    {
        label: "k_euler_a",
        value: 'k_euler_a'
    },
    {
        label: "k_dpm_2",
        value: 'k_dpm_2'
    },
    {
        label: "k_dpm_2_a",
        value: 'k_dpm_2_a'
    },
    {
        label: "k_dpm_fast",
        value: 'k_dpm_fast'
    },
    {
        label: "k_dpm_adaptive",
        value: 'k_dpm_adaptive'
    },
    {
        label: "k_dpmpp_2s_a",
        value: 'k_dpmpp_2s_a'
    },
    {
        label: "k_dpmpp_2m",
        value: 'k_dpmpp_2m'
    },
    {
        label: "dpmsolver",
        value: 'dpmsolver'
    },
    {
        label: "k_dpmpp_sde",
        value: 'k_dpmpp_sde'
    },
    {
        label: "DDIM",
        value: 'DDIM'
    }
  ];

  onMounted(() => {
      // 设置当前drawerWidth 宽度
      drawerWidth.value = window.innerWidth - 300;
      window.addEventListener('resize', handleResize);
  })

  // 窗口宽度变化
  const handleResize = () => {
      drawerWidth.value = window.innerWidth - 300;
  }

  const formSubmit =  async () => {
    const res = await sdControllerApi.generateText2Img(sdTxt2ImgPrompt)
    if(res.code === 200){
        const data = res.data;
        if(data.code === 1){
            checkTask(data.result);
        }
    }else {
        message.error(res.message);
    }

  }

  const loadPromptEvent = (prompt:string,negativePrompt:string) => {
      sdTxt2ImgPrompt.prompt = prompt;
      sdTxt2ImgPrompt.negativePrompt = negativePrompt;
      show.value = false;
  }

  let timeoutId = ref();// 保存当前的 setTimeout 的 id
  const checkTask = async (taskId:string) => {
      console.log("checkTask", taskId)
      const response = await sdControllerApi.checkTask(taskId);
      if(response.code === 200){
          const data = response.data;
          taskStatus.value = data.status;
          if (data.status !== "SUCCESS") {
              timeoutId.value = setTimeout(() => {
                  checkTask(taskId);
              }, 1000); // 每隔0.5秒调用一次 checkTask
          } else {
              clearTimeout(timeoutId.value); // 当任务完成时停止调用 checkTask
              imageSrc.value = "http://127.0.0.1:8066/filetransfer/preview?promptId="+taskId;

          }
      }else {
          clearTimeout(timeoutId.value); // 当任务完成时停止调用 checkTask
          imageSrc.value = "http://127.0.0.1:8066/filetransfer/preview?promptId="+taskId;
      }

  }

</script>
